package cn.virens.util.ztree.cutsom;

import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import cn.virens.util.shiro.Permission;
import cn.virens.util.ztree.CheckNode;
import cn.virens.util.ztree.Node;

/**
 * 自定义Ztree节点- 资源节点
 * 
 * @作者 :loioi
 * @创建时间 :2016年12月19日
 */
public class ResourceNode extends CheckNode<String> {
	private String permission;
	private Boolean bottomNode = true;

	public ResourceNode() {
		this.setpId("");
	}

	@Override
	public boolean addChildren(Node<String> node) {
		if (!(node instanceof ResourceNode)) return false;

		// 判断是不是下级的子节点
		if (CollectionUtils.isNotEmpty(super.getChildren())) {
			for (Node<String> node2 : super.getChildren()) {
				if (node2.addChildren(node)) {
					return true;
				}
			}
		}
		// 判断是不是this 的子节点
		if (StringUtils.startsWith(node.getId(), getId())) {
			return this._addChildren(node);
		}

		return false;
	}

	@Override
	protected boolean _addChildren(Node<String> node) {
		this.bottomNode = false;

		node.setpId(getId());

		return super._addChildren(node);
	}

	@Override
	public List<Node<String>> getChildren() {
		if (CollectionUtils.isEmpty(super.getChildren())) {
			this._addChildren(new PermissionNode(Permission.VIEW));
			this._addChildren(new PermissionNode(Permission.MANAGE));
		}

		return super.getChildren();
	}

	public String getPermission() {
		return permission;
	}

	public void setPermission(String permission) {
		this.permission = permission;
	}

	@Override
	public Boolean getChecked() {
		return StringUtils.isNotEmpty(this.permission);
	}

	public Boolean getBottomNode() {
		return bottomNode;
	}

	public void setBottomNode(Boolean bottomNode) {
		this.bottomNode = bottomNode;
	}

	public class PermissionNode extends CheckNode<String> {
		private Permission permission;

		public PermissionNode(Permission permission) {
			this.permission = permission;
		}

		@Override
		public String getId() {
			return permission.getIdentity();
		}

		@Override
		public String getpId() {
			return ResourceNode.this.getId();
		}

		@Override
		public String getName() {
			return permission.getText();
		}

		@Override
		public Boolean getChecked() {
			return permission.has(ResourceNode.this.getPermission());
		}

		public boolean getPermissionNode() {
			return true;
		}

		@Override
		public boolean addChildren(Node<String> node) {
			return false;
		}
	}
}
